package br.com.webservicedelivery.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import br.com.webservicedelivery.domain.Servicos;
import br.com.webservicedelivery.util.HibernateUtil;

public class ServicosDAO {
	public void salvar(Servicos servicos) {
		Session sessao = HibernateUtil.getSessionFactory().openSession();
		Transaction transacao = null;
		

		try {
			transacao = sessao.beginTransaction();
			sessao.save(servicos);
			transacao.commit();

		} catch (RuntimeException ex) {
			if (transacao != null) {
				transacao.rollback();
			}
			throw ex;

		} finally {

			sessao.close();

		}
		
	}

	@SuppressWarnings("unchecked")
	public List<Servicos> listar() {
		Session sessao = HibernateUtil.getSessionFactory().openSession();
		List<Servicos> servico = null;

		try {
			Query consulta = sessao.getNamedQuery("Servicos.listar");
			servico = consulta.list();

		} catch (RuntimeException ex) {
			throw ex;
		} finally {
			sessao.close();
		}

		return servico;
	}

	public Servicos buscarPorId(Long id) {
		Session sessao = HibernateUtil.getSessionFactory().openSession();
		Servicos servicos = null;

		try {
			Query consulta = sessao.getNamedQuery("Servicos.buscarPorId");
			consulta.setLong("id", id);

			servicos = (Servicos) consulta.uniqueResult();

		} catch (RuntimeException ex) {
			throw ex;
		} finally {
			sessao.close();
		}

		return servicos;
	}

	public void excluir(Servicos servicos) {
		Session sessao = HibernateUtil.getSessionFactory().openSession();
		Transaction transacao = null;

		try {
			transacao = sessao.beginTransaction();
			sessao.delete(servicos);
			transacao.commit();

		} catch (RuntimeException ex) {
			if (transacao != null) {
				transacao.rollback();
			}
			throw ex;

		} finally {

			sessao.close();

		}
	}

/*	public void excluir(Long id) {
		Session sessao = HibernateUtil.getSessionFactory().openSession();
		Transaction transacao = null;

		try {
			transacao = sessao.beginTransaction();
			Servicos servicos = buscarPorId(id);
			sessao.delete(servicos);
			transacao.commit();

		} catch (RuntimeException ex) {
			if (transacao != null) {
				transacao.rollback();
			}
			throw ex;

		} finally {

			sessao.close();

		}

	}*/

	public void editar(Servicos servicos) {
		Session sessao = HibernateUtil.getSessionFactory().openSession();
		Transaction transacao = null;

		try {
			transacao = sessao.beginTransaction();
			
			/*Servicos servicosEditar = buscarPorId(servicos.getId());
			servicosEditar.setTipo(servicos.getTipo());
			sessao.update(servicos);*/
			
			sessao.update(servicos);
			transacao.commit();

		} catch (RuntimeException ex) {
			if (transacao != null) {
				transacao.rollback();
			}
			throw ex;

		} finally {

			sessao.close();

		}
	}
}